#include "AtNetworkStream.h"

/**
 * 串口-读取指定结尾的字符
 * @param buf 字符缓冲区
 * @param lenght 最大字符长度
 * @param lastc 最后字符
 */
size_t AtNetworkStream::streamGet(char *buf, size_t lenght, int lastc) {
  size_t index = 0;

  while (lenght > 0 && index < lenght) {
    int tmp = this->_stream->read();
    if (tmp < 0 || tmp == lastc) {
      buf[index] = '\0';

      return index;
    }

    if (DEBUG_OUT && tmp >= 0) {
      Serial.write(tmp);
    }

    buf[index++] = tmp;
    buf[index] = '\0';

    AT_YIELD();
  }

  return index;
}

/**
 * 串口-读取Float
 * @param lastc 结束字符
 */
float AtNetworkStream::streamGetFloat(size_t len, char lastc) {
  char *buf = (char *)MEM_ALLOC(len + 1); // 申请临时内存
  float result = 0;                       // 返回值

  if (this->streamGet(buf, len, lastc)) {
    result = atof(buf);
  }

  free(buf);

  return result;
}

/**
 * 串口-读取Int
 * @param lastc 结束字符
 */
int AtNetworkStream::streamGetInt(size_t len, char lastc) {
  char *buf = (char *)MEM_ALLOC(len + 1); // 申请临时内存
  int result = 0;                         // 返回值

  if (this->streamGet(buf, len, lastc)) {
    result = atoi(buf);
  }

  free(buf);

  return result;
}

/**
 * 串口-释放缓冲区无效数据
 *  */
void AtNetworkStream::streamReleaseInvalidLegacyData() {
  while (this->_stream->available()) {
    int t = this->_stream->read();
    if (DEBUG_OUT && t >= 0) {
      Serial.write(t);
    }
  }
}

/**
 * 串口-跳过指定内容数据
 */
bool AtNetworkStream::streamSkipUntil(char c) {
  uint32_t expire_t = millis() + 1000L;

  while (this->_stream->read() != c) {
    if (expire_t < millis()) {
      return false;
    }

    AT_YIELD();
  }

  return true;
}